<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="单号" prop="outOrderNumber">
            <el-input
              @clear="handleQuery"
              v-model="queryParams.outOrderNumber"
              placeholder="请输入单号"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="项目名称" prop="projectName">
            <el-input
              @clear="handleQuery"
              v-model="queryParams.projectName"
              placeholder="请输入项目名称"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="类别" prop="category">
            <el-select v-model="queryParams.categoryId" placeholder="请选择类别" clearable @change="handleQuery">
              <el-option v-for="dict in fixed_category" :key="dict.id" :label="dict.category" :value="dict.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间段" prop="during">
            <el-date-picker
              @change="handleQuery"
              v-model="dateRange"
              type="daterange"
              value-format="YYYY-MM-DD"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:assetOutboundRecords:add']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" @click="handleUpdate()" v-hasPermi="['business:assetOutboundRecords:edit']">修改</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['business:assetOutboundRecords:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:assetOutboundRecords:export']"
              >导出表格</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="assetOutboundRecordsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="单号" align="center" prop="outOrderNumber" width="180" />
        <el-table-column label="类别" align="center" prop="category">
          <template #default="scope">
            <span>{{getCategory(scope.row.category)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="型号" align="center" prop="model" />
        <el-table-column label="单位" align="center" prop="unit" />
        <el-table-column label="单价" align="center" prop="univalence" />
        <el-table-column label="项目名称" align="center" prop="projectName" />
        <el-table-column label="出库数量" align="center" prop="outboundQuantity" />
        <el-table-column label="出库时间" align="center" prop="outboundTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.outboundTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['business:assetOutboundRecords:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['business:assetOutboundRecords:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="AssetOutboundRecords" lang="ts">
import { listAssetOutboundRecords, getAssetOutboundRecords, delAssetOutboundRecords, addAssetOutboundRecords, updateAssetOutboundRecords } from '@/api/business/assetOutboundRecords/index';
import { AssetOutboundRecordsVO, AssetOutboundRecordsQuery, AssetOutboundRecordsForm } from '@/api/business/assetOutboundRecords/types';
import { listAssetCategory } from '@/api/business/assetCategory/index';

const router = useRouter();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const fixed_category = ref([])
const xzqueryParams = ref<ProjectQuery>({
  type:undefined
})

const assetOutboundRecordsList = ref<AssetOutboundRecordsVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

const initFormData: AssetOutboundRecordsForm = {
  id: undefined,
  propertyAssetLedgerId: undefined,
  projectId: undefined,
  outOrderNumber: undefined,
  projectName: undefined,
  outboundQuantity: undefined,
  univalence: undefined,
  total: undefined,
  inventoryQuantity: undefined,
  outboundTime: undefined,
  remark: undefined,
}
const dateRange = ref(['', '']);
const data = reactive<PageData<AssetOutboundRecordsForm, AssetOutboundRecordsQuery>>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryId:undefined,
    // orderByColumn:'updateTime',
    // isAsc:'desc',
    type:undefined,
    propertyAssetLedgerId: undefined,
    projectId: undefined,
    outOrderNumber: undefined,
    projectName: undefined,
    outboundQuantity: undefined,
    univalence: undefined,
    total: undefined,
    inventoryQuantity: undefined,
    outboundTime: undefined,
    params: {
    }
  },
});

const { queryParams } = toRefs(data);

const getDateRange = (params: any, dateRange: any[]) =>{
  const search = params;
  search.params = typeof search.params === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
  dateRange = Array.isArray(dateRange) ? dateRange : [];
  search.beginTime = dateRange[0];
  search.endTime = dateRange[1];
  return search;
}

/** 查询资产出库记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAssetOutboundRecords(getDateRange(queryParams.value, dateRange.value));
  assetOutboundRecordsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value.categoryId = ''
  queryFormRef.value?.resetFields();
  dateRange.value=['', '']
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AssetOutboundRecordsVO[]) => {
  ids.value = selection.map(item => item.id);
  // single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  router.push({ path: '/FixedAssetManagement/FixedAssetManagementOutboundAdd', query: { type:'add' } })
}

/** 修改按钮操作 */
const handleUpdate = async (row?: AssetOutboundRecordsVO) => {
  router.push({ path: '/FixedAssetManagement/FixedAssetManagementOutboundAdd', query: { type:'edit',id: row.id} })
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('business/assetOutboundRecords/export', {
    ...queryParams.value
  }, `出库记录_${timestampToDatetime(new Date().getTime())}.xlsx`)
}

const timestampToDatetime = (timestamp) => {
  const dateObj = new Date(timestamp);
  const year = dateObj.getFullYear();
  const month = dateObj.getMonth() + 1;
  const day = dateObj.getDate();
  const hours = dateObj.getHours();
  const minutes = dateObj.getMinutes();
  const seconds = dateObj.getSeconds();
  return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
}
/** 删除按钮操作 */
const handleDelete = async (row?: AssetOutboundRecordsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除资产出库记录编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delAssetOutboundRecords(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

const getCategory = (data) =>{
  if (data && fixed_category.value) {
    let obj = fixed_category.value.find(item=>item.id ==data)
    return obj?.category
  }
}

onMounted(() => {
  getList();
  listAssetCategory(xzqueryParams.value).then(res=> {
    if(res.code == 200) {
      fixed_category.value = res.rows
    }
  })
});
</script>
